import axios from 'axios';
import {useEffect, useState} from 'react';
import { notification } from 'antd'
const usePublish = (type) => {
    const [dataSource, setdataSource] = useState([]);
    const { username } = JSON.parse(localStorage.getItem('token'))
    useEffect(() => {
        axios.get(`/news?author=${username}&publishState=${type}&_expand=category`).then(res=>{
            setdataSource(res.data)
        })
    }, [username,type])
    //移除当前ID
    const setfilter = (id) => {
        setdataSource(dataSource.filter(item=>item.id!==id))
    }
    // 发布按钮
    const handleUnpublished = (id)=>{
        setfilter(id)
        axios.patch(`/news/${id}`,{
            publishState: 2,
            publishTime: Date.now()
        }).then(res=>{
            notification.info({
                message: `发布成功`,
                description:`您可以去发布中查看您发布管理的新闻`,
                placement:'bottomRight',
              });
        })
    }
    // 删除按钮
    const handleSunset = (id)=>{
        setfilter(id)
        axios.delete(`/news/${id}`).then(res=>{
            notification.info({
                message: `删除成功`,
                description:`您已经了您下线的新闻`,
                placement:'bottomRight',
              });
        })
    }

    return {
        dataSource,
        handleUnpublished,
        handleSunset,
    }
};

export default usePublish;